package Server;

import Model.CustomHashtable;
import Model.User;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.*;
import javax.swing.JOptionPane;

public class MyConnect {

    ObjectInputStream inObject;
    ObjectOutputStream outObject;
    public static String url, username, password;

    public MyConnect(ObjectInputStream inObject, ObjectOutputStream outObject) {
        this.inObject = inObject;
        this.outObject = outObject;

    }

    public static Connection getConnect() {
      //  url = "jdbc:sqlserver://127.0.0.1:1433;databasename=DVTLib";
      //  username = "sa";
      //  password = "vanduong";
        Connection cn = null;
        try {
            //chon va dang ky driver
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            //2.tao ket noi tu ung dung java -> SQL server
            cn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException ex) {
            JOptionPane.showMessageDialog(null, "getConnect: " + ex.getMessage());
        }
        return cn;
    }

    MyConnect() {
    }

    public boolean isAuthentication(User user) {
        Connection con = MyConnect.getConnect();
        try {
            String sql = "select Role from Administrator where Password='" + user.getPassword() + "' and Username='" + user.getUsername() + "'";
            Statement stm = con.createStatement();
            ResultSet rs = stm.executeQuery(sql);
            if (rs.next()) {
                user.setRole(rs.getString(1));
                return true;
            }
            return false;
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "isAuthentication: " + e.getMessage());
            return false;
        }

    }

   static public boolean testConnection(String serverName, String Port, String databaseName, String userName, char[] Passwords) {
        try {
            String Pass = "";
            Connection conn;
            for (int i = 0; i < Passwords.length; i++) {
                Pass += Passwords[i];
            }
            String connectURL = "";
            connectURL = "jdbc:sqlserver://" + serverName + ":" + Port + ";databaseName=" + databaseName;
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            conn = DriverManager.getConnection(connectURL, userName, Pass);
            if (conn == null) {
                return false;
            } else {
                MyConnect.url = connectURL;
                MyConnect.username = userName;
                MyConnect.password = Pass;
                return true;
            }
        } catch (Exception ex) {
            return false;
        }
    }

    static public boolean saveConfig(String servername, String port, String databasename, String username, char[] passwords) {
        if (testConnection(servername, port, databasename, username, passwords)) {
            String fileConfig = "config.bin";
            CustomHashtable data = new CustomHashtable();
            String pass = "";
            for (int i = 0; i < passwords.length; i++) {
                pass += passwords[i];
            }
            try {
                File file = new File(fileConfig);
                if (file.exists()) {
                    FileInputStream fis = new FileInputStream(file);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    if (fis.available() > 0) {
                        data = (CustomHashtable) ois.readObject();
                    }
                    ois.close();
                    fis.close();
                }
                FileOutputStream fos = new FileOutputStream(fileConfig, false);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                data.put("servername", servername);
                // data.put("instance",instance);
                data.put("port", port);
                data.put("databasename", databasename);
                data.put("usernamedb", username);
                data.put("passdb", pass);
                oos.writeObject(data);
                oos.close();
                fos.close();

            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "SaveConfig: " + ex.getMessage());
                return false;
            }
            return true;
        } else {
            return false;
        }
    }
    static public boolean connecting() {

        try {
            String fileConfig = "config.bin";
            File file = new File(fileConfig);
            CustomHashtable data = new CustomHashtable();
            if (file.exists()) {
                FileInputStream fis = new FileInputStream(file);
                ObjectInputStream ois = new ObjectInputStream(fis);
                if (fis.available() > 0) {
                    data = (CustomHashtable) ois.readObject();
                }
                ois.close();
                fis.close();
            }
            String ServerName = data.get("servername").toString();
            String Port = data.get("port").toString();
            String DatabaseName = data.get("databasename").toString();
            String UserName = data.get("usernamedb").toString();
            String Pass = data.get("passdb").toString();
            String connectURL = "";
            connectURL = "jdbc:sqlserver://" + ServerName + ":" + Port + ";databaseName=" + DatabaseName;
            MyConnect.url = connectURL;
            MyConnect.username = UserName;
            MyConnect.password = Pass;
            if (UserName.equals("")) {
                return false;
            } else {
                char[] Passwords = Pass.toCharArray();
                if (testConnection(ServerName, Port, DatabaseName, UserName, Passwords)) {
                    return true;
                }
                else{
                    return false;
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public void showMyAccount() {
        try {

            String username = (String) inObject.readObject();
            String sql = "Select * from Administrator where Username = '" + username + "';";
            Connection con = getConnect();
            Statement stm = con.createStatement();
            ResultSet rs = stm.executeQuery(sql);
            rs.next();
            User userSelected = new User(rs.getString(1), rs.getString(2));
            userSelected.setRole(rs.getString(3));
            outObject.writeObject(userSelected);





        } catch (SQLException | IOException | ClassNotFoundException ex) {
            System.out.println(ex);
        }

    }

    public void changePassword() {
        try {
            User userSelected = (User) inObject.readObject();//nhan doi tuong login do client goi         
            outObject.writeObject(ChangePassword(userSelected));      //goi thong bao cho client                
        } catch (IOException | ClassNotFoundException ex) {
            System.out.println(ex);
        }
    }

    public boolean ChangePassword(User userSelected) {
        try {

            Connection cn = getConnect();
            String sql = "update Administrator set Password=? where Username=? ";
            PreparedStatement pst = cn.prepareStatement(sql);
            pst.setString(1, userSelected.getPassword());
            pst.setString(2, userSelected.getUsername());
            pst.executeUpdate();
            pst.close();
            cn.close();

        } catch (Exception ex) {
            return false;
        }
        return true;
    }
}
